
import pymysql
import json
from hashlib import md5
import redis
import requests


# 操作数据库类
class cxt_connetMyql(object):
    def __init__(self, host, user, password, db, port, charset='utf8'):
        self.host = host
        self.user = user
        self.password = password
        self.db = db
        self.port = port
        self.charset = charset
        self.__getCursor()

    def __getCursor(self):
        try:
            conn = pymysql.connect(self.host, self.user, self.password, self.db, self.port, self.charset,
                                        use_unicode=True)
            self.conn = conn
        except Exception as e:
            print('数据库链接失败:', e)
        finally:
            self.cursor = self.conn.cursor()
            # 设置游标的编码
            self.cursor.execute('SET NAMES utf8;')
            self.cursor.execute('SET CHARACTER SET utf8;')
            self.cursor.execute('SET character_set_connection=utf8;')

    def executeSelectSql(self, sql):
        try:
            self.cursor.execute(sql)
        except Exception as e:
            print('执行查询SQL失败,错误信息:', e)
        finally:
            return self.cursor.fetchall()

    def executeOtherSql(self, sql):
        try:
            self.cursor.execute(sql)
        except Exception as e:
            print('执行SQL语句失败,错误信息:', e)
        finally:
            self.conn.commit()

    def __del__(self):

        self.cursor.close()
        self.conn.close()


# 字典转字符串
def cxt_myJson(dict):
    return json.dumps(dict, ensure_ascii=False)


# md5加密
def cxt_md5Tool(str):
    md = md5()
    md.update(str.encode())
    mstr = md.hexdigest()
    return mstr

# 操作Redis类
class cxt_myRedis(object):
    def __init__(self, host, password, port):
        self.pool = redis.ConnectionPool(host=host, password=password, port=port)
        self.r = redis.StrictRedis(connection_pool=self.pool)

    def get(self, k):
        return self.r.get(k)

    def set(self, k, v):
        self.r.set(k, v)

    def delete(self, k):
        self.r.delete(k)

    # 批量模糊查询keys
    def fuzzyGet(self, k):
        return self.r.keys(k)

        # # 批量模糊删除keys
        # def fuzzyDelete(self, k):
        #     return self.r.delete(*self.r.keys(pattern='*k*'))


# # 示例:
# myredis = cxt_myRedis(**REDIS_INFO)
# # res1 = myredis.get('send_dynamic_times_190117_17600176673')
# # res2 = myredis.fuzzyGet('*17600176673*')
# res = myredis.delete('user_index_3554')
# print(res)


'''
封装请求方法
'''
def cxt_myRequest(method, url, data, headers):
    try:
        if method.upper == 'GET':
            res = requests.get(url, data, headers).json()
        elif method.upper == 'POST':
            res = requests.post(url, data, headers).json()
    except Exception as e:
        return '出错了，错误是%s' % e
    finally:
        return res
